package com.atguigu.gulimall.order.rabbit.config;

import com.atguigu.gulimall.order.rabbit.constant.OrderRabbitConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author lhj
 * @Date 2024/5/18 22:13
 */
@Component
@Configuration
public class OrderRabbitConfig {

    /**
     * 声明订单交换机
     *
     * @return
     */
    @Bean
    public TopicExchange orderEventExchange() {
        return ExchangeBuilder.topicExchange(OrderRabbitConstant.ORDER_EVENT_EXCHANGE).durable(true).build();
    }

    /**
     * 声明订单延迟队列
     *
     * @return
     */
    @Bean
    public Queue orderDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", OrderRabbitConstant.ORDER_EVENT_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", OrderRabbitConstant.ORDER_RELEASE_ORDER_ROUTING_KEY);
        arguments.put("x-message-ttl", 60000);
        return QueueBuilder.durable(OrderRabbitConstant.ORDER_DELAY_QUEUE).withArguments(arguments).build();
    }

    /**
     * 交换机绑定延迟队列
     *
     * @param orderEventExchange 交换机
     * @param orderDelayQueue    延迟队列
     * @return
     */
    @Bean
    public Binding orderDelayBinding(@Qualifier(value = "orderEventExchange") TopicExchange orderEventExchange,
                                     @Qualifier(value = "orderDelayQueue") Queue orderDelayQueue) {
        return BindingBuilder.bind(orderDelayQueue).to(orderEventExchange).with(OrderRabbitConstant.CREATE_ORDER_ROUTING_KEY);
    }

    /**
     * 声明订单释放队列
     *
     * @return
     */
    @Bean
    public Queue orderReleaseOrderQueue() {
        return QueueBuilder.durable(OrderRabbitConstant.ORDER_RELEASE_ORDER_QUEUE).build();
    }

    /**
     * 交换机绑定订单释放队列
     *
     * @param orderEventExchange     交换机
     * @param orderReleaseOrderQueue 释放队列
     * @return
     */
    @Bean
    public Binding orderReleaseOrderBinding(@Qualifier(value = "orderEventExchange") TopicExchange orderEventExchange,
                                            @Qualifier(value = "orderReleaseOrderQueue") Queue orderReleaseOrderQueue) {
        return BindingBuilder.bind(orderReleaseOrderQueue).to(orderEventExchange).with(OrderRabbitConstant.ORDER_RELEASE_ORDER_ROUTING_KEY);
    }

    /**
     * 绑定库存解锁队列
     * @return
     */
    @Bean
    public Binding orderReleaseOtherBinding() {
        return new Binding(OrderRabbitConstant.STOCK_RELEASE_QUEUE,
                Binding.DestinationType.QUEUE,
                OrderRabbitConstant.ORDER_EVENT_EXCHANGE,
                OrderRabbitConstant.ORDER_RELEASE_OTHER_ROUTING_KEY,
                null
        );
    }

}
